package com.breeze.lib

import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.TextView

/**
 * 用于保存需要换肤的View和其支持换肤的属性及属性值
 */
class SkinAttribute {
    private val mSkinViews = arrayListOf<SkinView>()
    fun look(view: View, attr: AttributeSet) {
        val skinView = SkinView()
        skinView.view = view

        val skinAttrs = arrayListOf<Pair<String, Int>>()
        for (i in 0 until attr.attributeCount) {
            val attributeName = attr.getAttributeName(i)
            if (SkinManager.supportAttribute.contains(attributeName)) {
                // 取值可能为 @2130837590、#具体色值、?2130837590 三种情况
                val attributeValue = attr.getAttributeValue(i)
                // 比如color 以#开头表示写死的颜色 不可用于换肤
                if (attributeValue.startsWith("#")) {
                    continue
                }
                var resId = 0
                if (attributeValue.startsWith("@")) {
                    resId = Integer.parseInt(attributeValue.substring(1))
                } else {
                    // TODO: 处理 ?attr情况
                }
                skinAttrs.add(Pair(attributeName, resId))
            }
        }
        skinView.skinAttrs = skinAttrs
        mSkinViews.add(skinView)
    }

    fun applySkin() {
        for (mSkinView in mSkinViews) {
            applySkin(mSkinView.view, mSkinView.skinAttrs)
        }
    }

    private fun applySkin(view: View, skinAttrs: ArrayList<Pair<String, Int>>) {
        for (skinAttr in skinAttrs) {
            // 根据属性id拿到Skin包中对应的资源设置给view
            val attributeName = skinAttr.first
            val resId = skinAttr.second
            when (attributeName) {
                // background，src 都有可能是 @color 也可能是 @drawable
                "background" -> {
                    val background = SkinResources.getBackground(resId)
                    if (background is Int) {
                        view.setBackgroundColor(background)
                    } else {
                        view.background = background as Drawable?
                    }
                }
                "src" -> {
                    val background = SkinResources.getBackground(resId)
                    if (background is Int) {
                        (view as ImageView).setImageDrawable(ColorDrawable(background))
                    } else {
                        (view as ImageView).setImageDrawable(background as Drawable)
                    }
                }
                "textColor" -> {
                    (view as TextView).setTextColor(SkinResources.getColorStateList(resId))
                }
            }
        }
    }

    class SkinView {
        lateinit var view: View

        // Pair中保存属性及对应的resId
        lateinit var skinAttrs: ArrayList<Pair<String, Int>>
    }
}